<template>
	<view class="container">
		<!-- 聊天内容区域 -->
		<scroll-view 
			class="chat-content" 
			scroll-y 
			:scroll-into-view="scrollToMessage"
			:scroll-with-animation="true"
			:scroll-anchoring="true"
			@scrolltoupper="loadMoreMessages"
			@scroll="onScroll"
			@scrolltolower="onScrollToLower">
			<view class="loading" v-if="isLoading">加载中...</view>
			<view class="chat-list">
				<view 
					class="chat-item" 
					v-for="(item, index) in messageList" 
					:key="index" 
					:class="{'self': item.isSelf}"
					:id="'msg-' + item.id">
					<view class="avatar" v-if="!item.isSelf">
						<image :src="passengerAvatar" mode="aspectFill"></image>
					</view>
					<view class="message-content">
						<view class="message-bubble" :class="{'self': item.isSelf}">
							<!-- 文本消息 -->
							<text v-if="item.type === 'text'" class="message-text">{{item.content}}</text>
							<!-- 语音消息 -->
							<view v-else-if="item.type === 'voice'" class="voice-message" @tap="playVoice(item)">
								<image src="https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/voice1.png" mode="aspectFit" style="height: 30px;width: 30px;"></image>	
								<text class="voice-duration">{{item.duration}}''</text>
							</view>
							<!-- 图片消息 -->
							<image v-else-if="item.type === 'image'" 
								:src="item.content" 
								mode="widthFix" 
								class="message-image"
								@tap="previewImage(item.content)">
							</image>
						</view>
						<text class="message-time">{{item.time}}</text>
					</view>
					<view class="avatar" v-if="item.isSelf">
						<image :src="driverAvatar" mode="aspectFill"></image>
					</view>
				</view>
			</view>
			<!-- 用于滚动到底部的锚点 -->
			<view id="scroll-bottom" class="scroll-bottom"></view>
		</scroll-view>
		
		<!-- 固定底部输入区域 -->
		<view class="input-area fixed">
			<view class="input-box">
				<view class="voice-btn" @tap="toggleVoiceInput">
					<image :src="isVoiceInput? 'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/keyboard.png' : 'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/voice.png'" mode="aspectFit"></image>
				</view>
				<!-- 文本输入框 -->
				<input v-if="!isVoiceInput" 
					class="text-input" 
					type="text" 
					v-model="inputMessage" 
					:focus="inputFocus"
					:adjust-position="false"
					@confirm="sendTextMessage"
					placeholder="请输入消息" />
				<!-- 语音输入按钮 -->
				<view v-else 
					class="voice-input" 
					@touchstart="startRecording" 
					@touchend="stopRecording"
					@touchcancel="cancelRecording">
					{{isRecording ? '松开发送' : '按住说话'}}
				</view>
				<view class="emoji-btn" @tap="toggleEmojiPanel">
					<image src="https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/expression.png" mode="aspectFit"></image>
				</view>
				<view class="more-btn" @tap="toggleMorePanel">
					<image src="https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/set.png" mode="aspectFit"></image>
				</view>
			</view>
			
			<!-- 更多功能面板 -->
			<view class="more-panel" v-if="showMorePanel">
				<view class="panel-item" @tap="chooseImage">
					<image src="https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/picture.png" mode="aspectFit"></image>
					<text>图片</text>
				</view>
				<view class="panel-item" @tap="makePhoneCall">
					<image src="https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/phone.png" mode="aspectFit"></image>
					<text>电话</text>
				</view>
				<view class="panel-item" @tap="showLocation">
					<image src="https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/location.png" mode="aspectFit"></image>
					<text>位置</text>
				</view>
			</view>
		</view>
		
		<!-- 录音提示 -->
		<view class="recording-tip" v-if="isRecording">
			<view class="recording-icon">
				<image src="https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/voice.png" mode="aspectFit"></image>
			</view>
			<text class="recording-text">正在录音...</text>
		</view>
		<!-- 表情面板 -->
		<view class="emoji-panel" v-if="showEmojiPanel">
			<view class="emoji-item" v-for="(emoji, index) in emojiList" :key="index" @tap="insertEmoji(emoji)">
				<image :src="emoji" mode="aspectFit"></image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 乘客信息
				passengerName: '张先生',
				passengerAvatar: '/static/images/default-avatar.png',
				orderNo: 'DD202403200001',
				
				// 司机信息
				driverAvatar: '/static/images/driver-avatar.png',
				
				// 聊天相关
				messageList: [],
				scrollTop: 0,
				isLoading: false,
				page: 1,
				
				// 输入相关
				inputMessage: '',
				inputFocus: false,
				isVoiceInput: false,
				isRecording: false,
				showMorePanel: false,
				
				// 录音相关
				recorderManager: null,
				voiceFilePath: '',
				
				// 修改滚动相关数据
				scrollToMessage: '',
				lastMessageId: '',
				isScrolling: false,
				scrollTimer: null,
				isFirstLoad: true, // 添加首次加载标记
				showEmojiPanel: false,
				emojiList: [
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji1.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji2.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji3.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji4.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji5.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji6.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji7.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji8.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji9.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji10.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji11.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji12.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji13.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji14.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji15.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji16.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji17.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji18.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji19.png',
					'https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/emoji/emoji20.png'
				]
			}
		},
		onLoad(options) {
			// 获取订单号和乘客信息
			if (options.orderNo) {
				this.orderNo = options.orderNo
			}
			this.initRecorder()
			this.loadMessages()
			this.isFirstLoad = true
		},
		onShow() {
			// 页面显示时滚动到底部
			this.$nextTick(() => {
				this.scrollToBottom()
			})
		},
		watch: {
			// 优化消息列表监听
			messageList: {
				handler(newVal) {
					if (newVal.length > 0) {
						const lastMessage = newVal[newVal.length - 1]
						this.lastMessageId = 'msg-' + lastMessage.id
						// 首次加载或发送新消息时滚动到底部
						if (this.isFirstLoad || lastMessage.isSelf) {
							this.$nextTick(() => {
								this.scrollToBottom()
							})
							this.isFirstLoad = false
						}
					}
				},
				deep: true
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 显示更多选项
			showMoreOptions() {
				uni.showActionSheet({
					itemList: ['清空聊天记录', '投诉乘客', '拉黑乘客'],
					success: (res) => {
						switch (res.tapIndex) {
							case 0:
								this.clearMessages()
								break
							case 1:
								this.reportPassenger()
								break
							case 2:
								this.blockPassenger()
								break
						}
					}
				})
			},
			
			// 加载聊天记录
			loadMessages() {
				// 模拟数据，实际应该调用API
				const mockMessages = Array(10).fill().map((_, index) => ({
					id: Date.now() + index,
					type: ['text', 'voice', 'image'][Math.floor(Math.random() * 3)],
					content: index % 2 === 0 ? '您好，我是您的司机' : '好的，我马上到',
					duration: Math.floor(Math.random() * 10) + 1,
					time: '14:30',
					isSelf: index % 2 === 0
				}))
				this.messageList = mockMessages
				// 首次加载后滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom()
				})
			},
			
			// 加载更多消息
			loadMoreMessages() {
				if (this.isLoading) return
				this.isLoading = true
				// 模拟加载更多
				setTimeout(() => {
					const moreMessages = Array(5).fill().map((_, index) => ({
						id: Date.now() - (this.page * 5 + index), // 添加唯一id
						type: ['text', 'voice', 'image'][Math.floor(Math.random() * 3)],
						content: '历史消息' + (this.page * 5 + index),
						duration: Math.floor(Math.random() * 10) + 1,
						time: '14:30',
						isSelf: index % 2 === 0
					}))
					this.messageList = [...moreMessages, ...this.messageList]
					this.isLoading = false
					this.page++
				}, 1000)
			},
			
			// 发送文本消息
			sendTextMessage() {
				if (!this.inputMessage.trim()) return
				const message = {
					id: Date.now(),
					type: 'text',
					content: this.inputMessage,
					time: this.formatTime(new Date()),
					isSelf: true
				}
				this.messageList.push(message)
				this.inputMessage = ''
				// 发送消息后立即滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom()
				})
			},
			
			// 初始化录音管理器
			initRecorder() {
				// 检查录音权限
				uni.authorize({
					scope: 'scope.record',
					success: () => {
						this.initRecorderManager()
					},
					fail: () => {
						uni.showModal({
							title: '提示',
							content: '需要录音权限才能发送语音消息，是否去设置？',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting()
								}
							}
						})
					}
				})
			},
			
			// 初始化录音管理器
			initRecorderManager() {
				this.recorderManager = uni.getRecorderManager()
				
				// 监听录音开始事件
				this.recorderManager.onStart(() => {
					console.log('录音开始')
				})
				
				// 监听录音结束事件
				this.recorderManager.onStop((res) => {
					console.log('录音结束', res)
					if (res.duration < 1000) {
						uni.showToast({
							title: '录音时间太短',
							icon: 'none'
						})
						return
					}
					
					this.voiceFilePath = res.tempFilePath
					// 添加消息ID
					const message = {
						id: Date.now(),
						type: 'voice',
						content: this.voiceFilePath,
						duration: Math.floor(res.duration / 1000),
						time: this.formatTime(new Date()),
						isSelf: true
					}
					this.messageList.push(message)
					this.scrollToBottom()
				})
				
				// 监听录音错误事件
				this.recorderManager.onError((res) => {
					console.error('录音错误：', res)
					uni.showToast({
						title: '录音失败，请重试',
						icon: 'none'
					})
					this.isRecording = false
				})
				
				// 监听录音中断事件
				this.recorderManager.onInterruptionBegin(() => {
					console.log('录音因为受到系统占用而被中断')
					uni.showToast({
						title: '录音被中断',
						icon: 'none'
					})
					this.isRecording = false
				})
				
				// 监听录音结束事件
				this.recorderManager.onInterruptionEnd(() => {
					console.log('录音中断结束')
				})
				
				// 监听录音帧数据
				this.recorderManager.onFrameRecorded((res) => {
					const { frameBuffer, isLastFrame } = res
					console.log('录音帧数据：', frameBuffer, isLastFrame)
				})
			},
			
			// 开始录音
			startRecording() {
				// 检查是否正在录音
				if (this.isRecording) {
					return
				}
				
				// 检查录音权限
				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.record']) {
							uni.authorize({
								scope: 'scope.record',
								success: () => {
									this.startRecord()
								},
								fail: () => {
									uni.showModal({
										title: '提示',
										content: '需要录音权限才能发送语音消息，是否去设置？',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							})
						} else {
							this.startRecord()
						}
					}
				})
			},
			
			// 开始录音的具体实现
			startRecord() {
				this.isRecording = true
				this.recorderManager.start({
					duration: 60000, // 最长录音时间，单位ms
					format: 'mp3',
					sampleRate: 16000,
					numberOfChannels: 1,
					encodeBitRate: 48000,
					frameSize: 50
				})
			},
			
			// 停止录音
			stopRecording() {
				if (!this.isRecording) {
					return
				}
				this.isRecording = false
				this.recorderManager.stop()
			},
			
			// 取消录音
			cancelRecording() {
				if (!this.isRecording) {
					return
				}
				this.isRecording = false
				this.recorderManager.stop()
				uni.showToast({
					title: '已取消录音',
					icon: 'none'
				})
			},
			
			// 播放语音
			playVoice(message) {
				if (!message.content) {
					uni.showToast({
						title: '语音文件不存在',
						icon: 'none'
					})
					return
				}
				
				const innerAudioContext = uni.createInnerAudioContext()
				innerAudioContext.src = message.content
				
				// 监听播放开始
				innerAudioContext.onPlay(() => {
					console.log('开始播放语音')
				})
				
				// 监听播放结束
				innerAudioContext.onEnded(() => {
					console.log('语音播放结束')
					innerAudioContext.destroy()
				})
				
				// 监听播放错误
				innerAudioContext.onError((res) => {
					console.error('语音播放错误：', res)
					uni.showToast({
						title: '语音播放失败',
						icon: 'none'
					})
					innerAudioContext.destroy()
				})
				
				innerAudioContext.play()
			},
			
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const message = {
							type: 'image',
							content: res.tempFilePaths[0],
							time: this.formatTime(new Date()),
							isSelf: true
						}
						this.messageList.push(message)
						this.scrollToBottom()
						// TODO: 上传图片并发送消息
					}
				})
			},
			
			// 预览图片
			previewImage(url) {
				uni.previewImage({
					urls: [url]
				})
			},
			
			// 拨打电话
			makePhoneCall() {
				uni.makePhoneCall({
					phoneNumber: '10086' // TODO: 替换为实际电话号码
				})
			},
			
			// 显示位置
			showLocation() {
				// TODO: 实现位置共享功能
				uni.showToast({
					title: '位置共享功能开发中',
					icon: 'none'
				})
			},
			
			// 切换语音输入
			toggleVoiceInput() {
				this.isVoiceInput = !this.isVoiceInput
				this.showMorePanel = false
			},
			
			// 切换表情面板
			toggleEmojiPanel() {
				this.showEmojiPanel = !this.showEmojiPanel
				this.showMorePanel = false
				if (this.showEmojiPanel) {
					this.inputFocus = false
				}
			},
			
			// 切换更多面板
			toggleMorePanel() {
				this.showMorePanel = !this.showMorePanel
			},
			
			// 清空聊天记录
			clearMessages() {
				uni.showModal({
					title: '提示',
					content: '确定要清空聊天记录吗？',
					success: (res) => {
						if (res.confirm) {
							this.messageList = []
							// TODO: 调用清空记录API
						}
					}
				})
			},
			
			// 投诉乘客
			reportPassenger() {
				uni.navigateTo({
					url: '/pages/report/report?orderNo=' + this.orderNo
				})
			},
			
			// 拉黑乘客
			blockPassenger() {
				uni.showModal({
					title: '提示',
					content: '确定要拉黑该乘客吗？',
					success: (res) => {
						if (res.confirm) {
							// TODO: 调用拉黑API
							uni.showToast({
								title: '已拉黑乘客'
							})
						}
					}
				})
			},
			
			// 优化滚动到底部方法
			scrollToBottom() {
				if (this.isScrolling) return
				this.isScrolling = true
				
				// 清除之前的定时器
				if (this.scrollTimer) {
					clearTimeout(this.scrollTimer)
				}
				
				// 使用setTimeout确保DOM更新后再滚动
				this.scrollTimer = setTimeout(() => {
					this.scrollToMessage = 'scroll-bottom'
					this.isScrolling = false
				}, 100)
			},
			
			// 监听滚动到底部事件
			onScrollToLower() {
				// 可以在这里处理滚动到底部的逻辑
				console.log('已滚动到底部')
			},
			
			// 监听滚动事件
			onScroll(e) {
				// 可以在这里处理滚动事件，比如判断是否滚动到底部
				const { scrollTop, scrollHeight, clientHeight } = e.detail
				// 如果滚动到底部，可以做一些处理
				if (scrollHeight - scrollTop - clientHeight < 50) {
					// 滚动到底部
				}
			},
			
			// 格式化时间
			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')
				return `${hours}:${minutes}`
			},
			
			// 插入表情
			insertEmoji(emoji) {
				const message = {
					id: Date.now(),
					type: 'image',
					content: emoji,
					time: this.formatTime(new Date()),
					isSelf: true
				}
				this.messageList.push(message)
				this.scrollToBottom()
			}
		}
	}
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
	padding-top: 88rpx; // 为固定导航栏留出空间
	padding-bottom: 180rpx; // 为固定输入区域留出空间
}

.nav-bar {
	height: 88rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	position: relative;
	z-index: 100;
	
	&.fixed {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
}

.back-btn, .more-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-title {
	flex: 1;
	text-align: center;
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	display: block;
}

.order-no {
	font-size: 24rpx;
	color: #999;
}

.chat-content {
	flex: 1;
	padding: 20rpx 20rpx;  // 减小左右内边距
	height: calc(100vh - 88rpx - 180rpx);
	box-sizing: border-box;
}

.loading {
	text-align: center;
	color: #999;
	font-size: 24rpx;
	padding: 20rpx 0;
}

.chat-list {
	padding-bottom: 20rpx;
	width: 100%;  // 修改宽度为100%
	margin: 0;  // 移除居中显示
}

.chat-item {
	display: flex;
	margin-bottom: 30rpx;
	padding: 0 10rpx;  // 添加左右内边距
	
	&.self {
		flex-direction: row-reverse;
		
		.message-bubble {
			background-color: #1B6EF3;
			color: #fff;
			border-radius: 20rpx 4rpx 20rpx 20rpx;
			margin-left: auto;
		}
	}
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	margin: 0 15rpx;  // 减小头像的左右间距
	
	image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}
}

.message-content {
	max-width: 65%;  // 调整消息内容最大宽度
}

.message-bubble {
	background-color: #fff;
	padding: 20rpx;
	border-radius: 4rpx 20rpx 20rpx 20rpx;
	margin-bottom: 10rpx;
	word-break: break-all;
}

.message-text {
	font-size: 28rpx;
	line-height: 1.4;
}

.voice-message {
	display: flex;
	align-items: center;
	min-width: 120rpx;
	
	.iconfont {
		font-size: 40rpx;
		margin: 0 10rpx;
	}
	
	.voice-duration {
		font-size: 24rpx;
	}
}

.message-image {
	max-width: 400rpx;
	border-radius: 8rpx;
}

.message-time {
	font-size: 24rpx;
	color: #999;
	margin: 0 20rpx;
}

.input-area {
	background-color: #fff;
	padding: 20rpx 30rpx; // 增加左右内边距
	border-top: 1rpx solid #eee;
	z-index: 100;
	
	&.fixed {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	}
}

.input-box {
	display: flex;
	align-items: center;
}

.voice-btn, .emoji-btn, .more-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.iconfont {
		font-size: 40rpx;
		color: #666;
	}
}

.text-input {
	flex: 1;
	height: 72rpx;
	background-color: #f5f5f5;
	border-radius: 36rpx;
	padding: 0 30rpx;
	margin: 0 20rpx;
	font-size: 28rpx;
}

.voice-input {
	flex: 1;
	height: 72rpx;
	background-color: #f5f5f5;
	border-radius: 36rpx;
	margin: 0 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #666;
}

.more-panel {
	position: absolute;
	bottom: 100%;
	left: 0;
	right: 0;
	background-color: #fff;
	display: flex;
	padding: 20rpx 30rpx;  // 减小内边距
	border-top: 1rpx solid #eee;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}

.panel-item {
	width: 25%;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 10rpx 0;  // 添加内边距
	
	image {
		width: 48rpx;  // 设置图标宽度
		height: 48rpx;  // 设置图标高度
		margin-bottom: 8rpx;  // 减小图标和文字的间距
	}
	
	text {
		font-size: 22rpx;  // 减小文字大小
		color: #666;
	}
}

.recording-tip {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	background-color: rgba(0, 0, 0, 0.7);
	border-radius: 12rpx;
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.recording-icon {
	width: 100rpx;
	height: 100rpx;
	background-color: #fff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 20rpx;
	
	.iconfont {
		font-size: 60rpx;
		color: #1B6EF3;
	}
}

.recording-text {
	color: #fff;
	font-size: 28rpx;
}

.scroll-bottom {
	height: 1rpx;
	width: 100%;
	visibility: hidden;
}

// 添加表情面板样式
.emoji-panel {
	position: fixed;
	bottom: 180rpx;
	left: 0;
	right: 0;
	height: 400rpx;
	background-color: #fff;
	display: flex;
	flex-wrap: wrap;
	padding: 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	z-index: 99;
	overflow-y: auto;
	
	.emoji-item {
		width: 20%;  // 每行5个表情
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 10rpx;
		box-sizing: border-box;
		
		image {
			width: 80rpx;
			height: 80rpx;
		}
	}
}
</style>
